package com.lepu.app.fun.tool.jqtx;

import java.text.SimpleDateFormat;
import java.util.Date;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.View.OnTouchListener;
import android.view.animation.AnimationUtils;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;
import android.widget.AbsListView.LayoutParams;

import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.utils.main.DateUtilBase;
import com.core.lib.utils.main.UtilityBase;
import com.eyzhs.app.R;
import com.lepu.app.fun.tool.jqtx.calendar.JqtxCalendarAdapter;
import com.lepu.app.widget.CustomTopBarNew;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewLeftLayoutListener;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewRightButtonListener;

public class JqtxMainResultActivity extends BaseFragmentActivity implements
		OnTopbarNewLeftLayoutListener,OnTopbarNewRightButtonListener {

	private static JqtxMainResultActivity mInstance = null;
	
	private GestureDetector gestureDetector = null;
	private JqtxCalendarAdapter calV = null;
	private ViewFlipper flipper = null;
	private GridView gridView = null;
	private int jumpMonth = 0; // 每次滑动，增加或减去一个月,默认为0（即显示当前月）
	private int jumpYear = 0; // 滑动跨越一年，则增加或者减去一年,默认为0(即当前年)
	private int year_c = 0;
	private int month_c = 0;
	private int day_c = 0;
	private String currentDate = "";
	/** 每次添加gridview到viewflipper中时给的标记 */
	private int gvFlag = 0;
	/** 当前的年月，现在日历顶端 */
	private TextView mCurrentMonth;

	private String mCurrentYearMonthString = "";
	private boolean mSlideLoadFlag = false;
	public String mCurrentSelectedString = "";

	@SuppressLint("SimpleDateFormat")
	public JqtxMainResultActivity() {

		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-d");
		currentDate = sdf.format(date); // 当期日期
		year_c = Integer.parseInt(currentDate.split("-")[0]);
		month_c = Integer.parseInt(currentDate.split("-")[1]);
		day_c = Integer.parseInt(currentDate.split("-")[2]);

		// 当前系统时间
		mCurrentYearMonthString = DateUtilBase.stringFromDate(new Date(),
				DateUtilBase.YEAR_MONTH);
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		
		mNeedStatusBar = false;
		mNeedSwipeBack = false;
		super.onCreate(savedInstanceState);
		setContentView(R.layout.jqtx_main_result_activity);

		mInstance = this;
		UtilityBase.setStatusBarRes(this, R.color.color_jqtx, true);
		init();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		
		mInstance = null;
	}
	
	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		
		//修改信息完成后，更新这个页面数据
		initData();
	}

	/**
	 * 添加页面动画，需要重写这个方法，
	 */
	@Override
	public void onBackPressed() {
		finish(true);
	}
	
	@Override
	public void onTopbarLeftLayoutSelected() {
		finish(true);
	}
	
	@Override
	public void onTopbarRightButtonSelected() {
		Intent intent = new Intent(this,JqtxMainActivity.class);
		intent.putExtra("IsModify", true);
		startActivity(intent, true);
	} 
	
	public static JqtxMainResultActivity getInstance()
	{
		return mInstance;
	}

	/**
	 * 初始化方法
	 */
	private void init() {
		// topbar
		CustomTopBarNew topbar = (CustomTopBarNew) findViewById(R.id.topbar);
		topbar.setTopbarTitle("经期提醒");
		topbar.setonTopbarNewLeftLayoutListener(this);
		topbar.setTopbarBackground(R.color.color_jqtx);
		
		topbar.setRightText("修改信息");
		topbar.setOnTopbarNewRightButtonListener(this);
		
		mCurrentMonth = (TextView) findViewById(R.id.currentMonth);

		gestureDetector = new GestureDetector(this, new MyGestureListener());
		flipper = (ViewFlipper) findViewById(R.id.flipper);
		
		initData();
	}
	
	private void initData() {
		flipper.removeAllViews();
		
		calV = new JqtxCalendarAdapter(this, getResources(),
				jumpMonth, jumpYear, year_c, month_c, day_c);
		addGridView();
		gridView.setAdapter(calV);
		flipper.addView(gridView, 0);

		addTextToTopTextView(mCurrentMonth);
	}
	
	public void viewClick(View v)
	{
		int rid = v.getId();
		
		switch (rid) {
		case R.id.nextLayout: // 下一个月

			mSlideLoadFlag = false;
			// enterNextMonth(gvFlag);
			requestEnterNextMonth();
			break;
		case R.id.preLayout: // 上一个月

			mSlideLoadFlag = false;
			// enterPrevMonth(gvFlag);
			requestEnterPreMonth();

			break;

		default:
			break;
		}
	}

	//=============================================
	/**
	 * 添加头部的年份 闰哪月等信息
	 * 
	 * @param view
	 */
	public void addTextToTopTextView(TextView view) {
		StringBuffer textDate = new StringBuffer();
		// draw = getResources().getDrawable(R.drawable.top_day);
		// view.setBackgroundDrawable(draw);
		textDate.append(calV.getShowYear()).append("年")
				.append(calV.getShowMonth()).append("月").append("\t");
		view.setText(textDate);
	}
	
	@SuppressLint({ "ClickableViewAccessibility", "InlinedApi" })
	private void addGridView() {
		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
				LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
		// 取得屏幕的宽度和高度
		//WindowManager windowManager = getWindowManager();
		//Display display = windowManager.getDefaultDisplay();
		//int Width = display.getWidth();
		//int Height = display.getHeight();

		gridView = new GridView(this);
		gridView.setNumColumns(7);
//		gridView.setColumnWidth(40);
//		// gridView.setStretchMode(GridView.STRETCH_COLUMN_WIDTH);
//		if (Width == 720 && Height == 1280) {
//			gridView.setColumnWidth(40);
//		}
		gridView.setGravity(Gravity.CENTER_VERTICAL);
		gridView.setSelector(new ColorDrawable(Color.TRANSPARENT));
		// 去除gridView边框
		gridView.setVerticalSpacing(10);// 1
		gridView.setHorizontalSpacing(1);
		gridView.setOnTouchListener(new OnTouchListener() {
			// 将gridview中的触摸事件回传给gestureDetector

			public boolean onTouch(View v, MotionEvent event) {
				return JqtxMainResultActivity.this.gestureDetector
						.onTouchEvent(event);
			}
		});

//		gridView.setOnItemClickListener(new OnItemClickListener() {
//
//			@Override
//			public void onItemClick(AdapterView<?> arg0, View arg1,
//					int position, long arg3) {
//
//				// 点击任何一个item，得到这个item的日期(排除点击的是周日到周六(点击不响应))
//				int startPosition = calV.getStartPositon();
//				int endPosition = calV.getEndPosition();
//				if (startPosition <= position + 7
//						&& position <= endPosition - 7) {
//					String scheduleDay = calV.getDateByClickItem(position)
//							.split("\\.")[0]; // 这一天的阳历
//					// String scheduleLunarDay =
//					// calV.getDateByClickItem(position).split("\\.")[1];
//					// //这一天的阴历
//					String scheduleYear = calV.getShowYear();
//					String scheduleMonth = calV.getShowMonth();
//
//					String selectedDateString = scheduleYear + "-"
//							+ scheduleMonth + "-" + scheduleDay;
//					LogUtilBase.LogD(null, "selectedDate===>"
//							+ selectedDateString);
//
//					Date selectedDate = DateUtilBase.dateFromString(
//							selectedDateString, "yyyy-M-d");
//					Date sysDate = DateUtilBase.dateFromString(currentDate,
//							"yyyy-M-d");
//
//					if (selectedDate.getTime() <= sysDate.getTime()) {
//						for (int i = 0; i < 42; i++) {
//							LinearLayout bgLayout = (LinearLayout) gridView
//									.findViewWithTag(i);
//							bgLayout.setSelected(false);
//						}
//
//						LinearLayout bgLayout = (LinearLayout) gridView
//								.findViewWithTag(position);
//						bgLayout.setSelected(true);
//
//						mCurrentSelectedString = DateUtilBase.stringFromDate(
//								selectedDate, DateUtilBase.YEAR_MONTH_DAY);
//					}else{
//						UIHelper.showToast(JqtxMainResultActivity.this, "请不要选择今天以后的日期");
//					}
//
//				}
//			}
//		});
		gridView.setLayoutParams(params);
	}
	
	/**
	 * 移动到上一个月
	 * 
	 * @param gvFlag
	 */
	private void enterPreMonth(int gvFlag) {
		calV = new JqtxCalendarAdapter(this, this.getResources(),
				jumpMonth, jumpYear, year_c, month_c, day_c);
		gridView.setAdapter(calV);
		gvFlag++;
		addTextToTopTextView(mCurrentMonth); // 移动到上一月后，将当月显示在头标题中
		flipper.addView(gridView, gvFlag);

		flipper.setInAnimation(AnimationUtils.loadAnimation(this,
				R.anim.grow_calendar_push_right_in));
		flipper.setOutAnimation(AnimationUtils.loadAnimation(this,
				R.anim.grow_calendar_push_right_out));
		flipper.showPrevious();
		flipper.removeViewAt(0);
	}

	private void requestEnterPreMonth() {
		addGridView(); // 添加一个gridView
		jumpMonth--; // 上一个月

		Date date = DateUtilBase.dateFromString(mCurrentYearMonthString,
				DateUtilBase.YEAR_MONTH);
		Date beforeDate = DateUtilBase.addDateOfMonth(date, -1);

		mCurrentYearMonthString = DateUtilBase.stringFromDate(beforeDate,
				DateUtilBase.YEAR_MONTH);

		//=================================
		//requestAlbumMonthDate(1);
		mCurrentSelectedString = "";
		
		int flag = 0;
		if (mSlideLoadFlag) {
			flag = 0;
		} else {
			flag = gvFlag;
		}
		enterPreMonth(flag);
	}

	/**
	 * 移动到下一个月
	 * 
	 * @param gvFlag
	 */
	private void enterNextMonth(int gvFlag) {
		calV = new JqtxCalendarAdapter(this, this.getResources(),
				jumpMonth, jumpYear, year_c, month_c, day_c);
		gridView.setAdapter(calV);
		addTextToTopTextView(mCurrentMonth); // 移动到下一月后，将当月显示在头标题中
		gvFlag++;
		flipper.addView(gridView, gvFlag);
		flipper.setInAnimation(AnimationUtils.loadAnimation(this,
				R.anim.grow_calendar_push_left_in));
		flipper.setOutAnimation(AnimationUtils.loadAnimation(this,
				R.anim.grow_calendar_push_left_out));
		flipper.showNext();
		flipper.removeViewAt(0);
	}

	private void requestEnterNextMonth() {
		addGridView(); // 添加一个gridView
		jumpMonth++; // 下一个月

		Date date = DateUtilBase.dateFromString(mCurrentYearMonthString,
				DateUtilBase.YEAR_MONTH);
		Date beforeDate = DateUtilBase.addDateOfMonth(date, 1);

		mCurrentYearMonthString = DateUtilBase.stringFromDate(beforeDate,
				DateUtilBase.YEAR_MONTH);

		//===============================
		//requestAlbumMonthDate(2);
		mCurrentSelectedString = "";
		
		int flag2 = 0;
		if (mSlideLoadFlag) {
			flag2 = 0;
		} else {
			flag2 = gvFlag;
		}
		enterNextMonth(flag2);
	}
	private class MyGestureListener extends SimpleOnGestureListener {
		@Override
		public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
				float velocityY) {
			//int gvFlag = 0; // 每次添加gridview到viewflipper中时给的标记
			if (e1.getX() - e2.getX() > 120) {
				// 像左滑动
				// enterNextMonth(gvFlag);

				mSlideLoadFlag = true;
				requestEnterNextMonth();
				return true;
			} else if (e1.getX() - e2.getX() < -120) {
				// 向右滑动
				// enterPrevMonth(gvFlag);

				mSlideLoadFlag = true;
				requestEnterPreMonth();
				return true;
			}
			return false;
		}
	}

}
